package com.njit.postbar;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Looper;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.njit.postbar.model.MailCode;
import com.njit.postbar.model.User;
import com.njit.postbar.utils.MD5;
import com.njit.postbar.utils.Remove;
import com.njit.postbar.utils.SendCode;
import com.sun.mail.util.MailConnectException;

import org.litepal.LitePal;

import java.util.List;
import java.util.Random;

import javax.mail.MessagingException;

import static com.njit.postbar.utils.Check.checkEmail;

public class Login extends Activity {
    private TextView title;
    private TextView tip;

    private Button login;
    private Button switchCode;
    private Button forgetPwd;
    private Button getCodeButton;
    private Button signUp;

    private ImageView headImage;
    private FrameLayout getCodeFrame;
    private FrameLayout passwordFrame;

    private View background;

    private ImageView clearEmail;
    private ImageView seePWD;
    private ImageView []bubble;

    private EditText email;
    private EditText password;
    private EditText codeText;

    private MailCode mailCode;

    private Thread [] threads;
    private MediaPlayer [] player;

    private boolean isCodeLogin = false;
    private boolean isShow = false;
    private boolean flag = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        Remove.removeTop(this);
        title = findViewById(R.id.login_title);
        tip = findViewById(R.id.please_clear_login);
        //按钮
        login = findViewById(R.id.login_confirm);
        switchCode = findViewById(R.id.switchCode_button);
        forgetPwd = findViewById(R.id.forget_pwd);
        signUp = findViewById(R.id.signUp_button);
        getCodeButton = findViewById(R.id.get_code_login);
        //头像
        headImage = findViewById(R.id.head_image_login);
        //邮箱验证码
        getCodeFrame = findViewById(R.id.login_code);
        //邮箱密码
        passwordFrame = findViewById(R.id.login_password);
        //图片按钮
        clearEmail = findViewById(R.id.clear_login);
        seePWD = findViewById(R.id.see_login);
        //背景
        background = findViewById(R.id.login_background);
        //文本框
        email = findViewById(R.id.login_email_text);
        password = findViewById(R.id.login_password_text);
        codeText = findViewById(R.id.login_code_text);
        //验证码和邮箱
        mailCode = new MailCode();
        //5个线程
        threads = new Thread[5];
        //开启动画线程
        animThread();
        //点击气泡三种音效
        touchListener();
        //表单监听器
        formEditListener();
        //获取验证码
        getCodeListener();
        //获取Intent传递过来的数据
        User user;
        Intent intent = getIntent();
        user = (User)intent.getSerializableExtra("user");
        initInfo(user);
    }
    public void initInfo(User user){
        if(user != null){
            title.setVisibility(View.INVISIBLE);
            headImage.setVisibility(View.VISIBLE);
            email.setText(user.getEmail());
            password.setText(user.getPassword());
            //设置用户头像
            Glide.with(this).load(user.getHeadImage()).into(headImage);
        }
    }
    /**
     *@author yuruiqiao
     *@date 2020/5/25
     *@description 获取邮箱验证码
     */
    public void getCodeListener(){
        getCodeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!checkEmail(email.getText().toString()))
                    Toast.makeText(getBaseContext(),"邮箱格式错误", Toast.LENGTH_LONG).show();
                else if(emailUnique())
                    Toast.makeText(getBaseContext(),"邮箱尚未注册", Toast.LENGTH_LONG).show();
                else{
                    //创建一个线程来发送邮箱
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            //生成六位验证码
                            mailCode.setCode((int)((Math.random()*9+1)*100000));
                            //验证码要和邮箱匹配
                            mailCode.setMailTo(email.getText().toString());
                            Looper.prepare();
                            try {
                                SendCode.send(email.getText().toString(), mailCode.getCode()+"");
                                getCodeButton.setVisibility(View.INVISIBLE);
                                tip.setVisibility(View.VISIBLE);
                                Toast.makeText(getBaseContext(),"验证码已发送", Toast.LENGTH_LONG).show();
                            } catch (MailConnectException me) {
                                Toast.makeText(getBaseContext(),"请检查网络连接", Toast.LENGTH_LONG).show();
                                me.printStackTrace();
                            } catch (MessagingException me){
                                Toast.makeText(getBaseContext(),"操作过于频繁", Toast.LENGTH_LONG).show();
                                me.printStackTrace();
                            } catch (Exception e){
                                Toast.makeText(getBaseContext(),"未知错误", Toast.LENGTH_LONG).show();
                                e.printStackTrace();
                            }
                            Looper.loop();
                        }
                    }).start();
                }
            }
        });
    }
    /**
     *@author yuruiqiao
     *@date 2020/5/27
     *@description 判断邮箱是否被注册
     */
    public boolean emailUnique(){
        List<User> users_email = LitePal.where("email = ?",email.getText().toString()).find(User.class);
        return users_email.size() <= 0;
    }
    /**
     *@author yuruiqiao
     *@date 2020/5/26
     *@description 动画函数
     */
    public AnimationSet animation(int left_start, int time, float size){
        int height = background.getHeight()/2+300;
        //位移动画
        TranslateAnimation ta = new TranslateAnimation(left_start, left_start, height, -1*height);
        //旋转动画
        RotateAnimation ra = new RotateAnimation(0, -90, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        //透明度变化
        AlphaAnimation aa = new AlphaAnimation(1, 0.3f);
        //缩放
        ScaleAnimation sa = new ScaleAnimation(size, size, size, size, ScaleAnimation.RELATIVE_TO_SELF, 1, ScaleAnimation.RELATIVE_TO_SELF, 1);
        //动画集合
        AnimationSet aSet = new AnimationSet(true);
        aSet.addAnimation(ra);
        aSet.addAnimation(ta);
        aSet.addAnimation(sa);
        aSet.addAnimation(aa);
        aSet.setDuration(time);
        aSet.setFillAfter(true);
        return aSet;
    }

    /**
     *@author yuruiqiao
     *@date 2020/5/26
     *@description 触屏出声音
     */
    public void touchListener(){
        player = new MediaPlayer[3];
        player[0] = MediaPlayer.create(Login.this,R.raw.yinxiao_1);
        player[1] = MediaPlayer.create(Login.this,R.raw.yinxiao_2);
        player[2] = MediaPlayer.create(Login.this,R.raw.yinxiao_3);
        //触屏事件
        background.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Random random = new Random();
                int num = random.nextInt(3);
                player[num].start();
                background.clearFocus();
                return false;
            }
        });
    }

    /**
     *@author yuruiqiao
     *@date 2020/5/26
     *@description 动画线程
     */
    public void animThread(){

        bubble = new ImageView[5];
        bubble[0] = findViewById(R.id.bubble1);
        bubble[1] = findViewById(R.id.bubble2);
        bubble[2] = findViewById(R.id.bubble3);
        bubble[3] = findViewById(R.id.bubble4);
        bubble[4] = findViewById(R.id.bubble5);

        threads[0] = new Thread(new Runnable() {
            @Override
            public void run() {
                circleAnim(bubble[0]);
            }
        });
        threads[0].start();
        threads[1] = new Thread(new Runnable() {
            @Override
            public void run() {
                circleAnim(bubble[1]);
            }
        });
        threads[1].start();
        threads[2] = new Thread(new Runnable() {
            @Override
            public void run() {
                circleAnim(bubble[2]);
            }
        });
        threads[2].start();
        threads[3] = new Thread(new Runnable() {
            @Override
            public void run() {
                circleAnim(bubble[3]);
            }
        });
        threads[3].start();
        threads[4] = new Thread(new Runnable() {
            @Override
            public void run() {
                circleAnim(bubble[4]);
            }
        });
        threads[4].start();
    }
    /**
     *@author yuruiqiao
     *@date 2020/5/26
     *@description 动画循环
     */
    public void circleAnim(ImageView view){
        while(flag){
            int time = (int)(Math.random()*10000)+3000;
            int left = (int)(Math.random()*1000)-500;
            float size = (float)Math.random()*0.6f+0.4f;
            view.startAnimation(animation(left,
                    time,size));
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     *@author yuruiqiao
     *@date 2020/5/27
     *@description 表单监听器
     */
    public void formEditListener(){
        //焦点监听器
        email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus && checkEmail(email.getText().toString())){
                    List<User> users_email = LitePal.where("email = ?",email.getText().toString()).find(User.class);
                    if(users_email.size() == 0){
                        title.setVisibility(View.VISIBLE);
                        headImage.setVisibility(View.INVISIBLE);
                        Toast.makeText(getBaseContext(),"邮箱尚未注册", Toast.LENGTH_LONG).show();
                    }
                    else{
                        User user = users_email.get(0);
                        //设置用户头像
                        Glide.with(Login.this).load(user.getHeadImage()).into(headImage);
                        title.setVisibility(View.INVISIBLE);
                        headImage.setVisibility(View.VISIBLE);
                    }
                }
                else if(!hasFocus && !checkEmail(email.getText().toString())){
                    title.setVisibility(View.VISIBLE);
                    headImage.setVisibility(View.INVISIBLE);
                }
            }
        });
        //清除邮箱
        clearEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                email.setText("");
                tip.setVisibility(View.INVISIBLE);
                getCodeButton.setVisibility(View.VISIBLE);
                title.setVisibility(View.VISIBLE);
                headImage.setVisibility(View.INVISIBLE);
            }
        });
        //密码可见性切换
        seePWD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果密码可见
                if(isShow){
                    //切换图标
                    seePWD.setBackground(getDrawable(R.drawable.ic_eye_close));
                    //设置密码不可见
                    password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                    //改变状态值为假
                    isShow = false;
                }else{
                    //切换图标
                    seePWD.setBackground(getDrawable(R.drawable.ic_eye));
                    //设置密码可见
                    password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    //改变状态值为真
                    isShow = true;
                }
            }
        });
        //切换登录方式
        switchCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //验证码登录状态,则将验证码登录变成不可见
                if(isCodeLogin){
                    getCodeFrame.setVisibility(View.INVISIBLE);
                    passwordFrame.setVisibility(View.VISIBLE);
                    switchCode.setText("邮箱验证码登录");
                    isCodeLogin = false;
                }else{
                    getCodeFrame.setVisibility(View.VISIBLE);
                    passwordFrame.setVisibility(View.INVISIBLE);
                    switchCode.setText("账号密码登录");
                    isCodeLogin = true;
                }
            }
        });
        //立即注册
        signUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //结束动画线程
                flag = false;
                //跳转注册
                Intent intent = new Intent();
                intent.setClass(Login.this,SignUp.class);
                intent.putExtra("email",email.getText().toString());
                startActivity(intent);
                finish();
            }
        });
        //忘记密码
        forgetPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getBaseContext(),"忘记密码用邮箱验证码登录", Toast.LENGTH_LONG).show();
            }
        });
        //登录按钮
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<User> users_email = LitePal.where("email = ?",email.getText().toString()).find(User.class);
                if(users_email.size() != 0){
                    User user = users_email.get(0);
                    String passwordMD5 = MD5.getMD5String(password.getText().toString());
                    //两种登录方式验证
                    if(user.getPassword().equals(passwordMD5) ||
                            codeText.getText().toString().equals(mailCode.getCode()+"")){
                        //结束动画线程
                        flag = false;
                        //跳转登录页面,传递对象
                        Intent intent = new Intent();
                        intent.setClass(Login.this,Index.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("user", user);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        finish();
                    } else if(isCodeLogin){
                        Toast.makeText(getBaseContext(),"验证码错误", Toast.LENGTH_LONG).show();
                    } else{
                        Toast.makeText(getBaseContext(),"邮箱或密码错误", Toast.LENGTH_LONG).show();
                    }
                }
                else if(checkEmail(email.getText().toString())){
                    Toast.makeText(getBaseContext(),"邮箱尚未注册", Toast.LENGTH_LONG).show();
                }
                else {
                    Toast.makeText(getBaseContext(),"邮箱格式错误", Toast.LENGTH_LONG).show();

                }
            }
        });
    }
}
